//
//  ViewController.m
//  悬浮按钮demo
//
//  Created by lzy on 2018/1/31.
//  Copyright © 2018年 lzy. All rights reserved.
//

#import "ViewController.h"
#import "JhtFloatingBall.framework/Headers/JhtFloatingBall.h"
#import "AppDelegate.h"
/** 屏幕 宽度 */
#define FrameW [UIScreen mainScreen].bounds.size.width

@interface ViewController () <JhtFloatingBallDelegate>

/** folatingball */
@property (nonatomic, strong) JhtFloatingBall *folatingball;

@property (nonatomic,strong)UIButton * btn;
@property (nonatomic, weak) CALayer *blueLayer;

@property (nonatomic,strong)UIView * viewOfType1;
@property (nonatomic,strong)NSDictionary * dicOfPOpView;

@end


/** 颜色转换  例：#000000 UIColorFromRGB(0x000000) */
#define UIColorFromRGB(rgbValue) [UIColor \
colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 \
green:((float)((rgbValue & 0xFF00) >> 8))/255.0 \
blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]

@implementation ViewController
-(UIView *)viewOfType1
{
    if(!_viewOfType1)
    {
        _viewOfType1 = [[UIView alloc]initWithFrame:self.view.bounds];
        _viewOfType1.userInteractionEnabled = YES;
        _viewOfType1.backgroundColor = [UIColor colorWithWhite:1.0 alpha:0.5];
        
        [ApplicationDelegate.window addSubview:_viewOfType1];
    }
    return _viewOfType1;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 创建UI界面
    [self createUI];
    
}

#pragma mark - UI
/** 创建UI界面 */
- (void)createUI {
    self.view.backgroundColor = UIColorFromRGB(0xCCBBAA);
    
    self.navigationController.navigationBar.translucent = NO;
    self.title = @"悬浮按钮";
    
    self.dicOfPOpView = @{@"type":@5};
    [self showTypeWithDic:self.dicOfPOpView];
  
    
}
//展现形式
-(void)showTypeWithDic:(id)dic
{
    int types = [dic[@"type"] intValue];
    if(types == 5)
    {
        [self showType5:dic];
    }else
    {
        [self showType:dic];
    }
   
}
//第一种展现形式
-(void)showType:(id)dic
{
//    https://img.jingjibang.cn/bs/service/1517283838061gz%E7%AE%A1%E7%90%86%E5%91%98.png
    int types = [dic[@"type"] intValue];
    
    UIImage * images = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@"https://img.jingjibang.cn/bs/service/1517283838061gz%E7%AE%A1%E7%90%86%E5%91%98.png"]]];
    UIImageView * imageOfView = [[UIImageView alloc]init];
    imageOfView.userInteractionEnabled = YES;
    if(types == 1)
    {
       imageOfView.frame = CGRectMake(self.viewOfType1.center.x-(images.size.width/2), self.viewOfType1.center.y-(images.size.height/2), images.size.width, images.size.height);
    }else if (types == 2)
    {
        imageOfView.frame = CGRectMake((self.viewOfType1.frame.size.width-images.size.width)/2, self.viewOfType1.frame.size.height-images.size.height, images.size.width, images.size.height);
    }else if (types == 3)
    {
        imageOfView.frame = CGRectMake((self.viewOfType1.frame.size.width-images.size.width)/2, 0, images.size.width, images.size.height);
    }else if (types == 4)
    {
        imageOfView.frame = self.viewOfType1.bounds;
    }
    
    imageOfView.image = images;
    [self.viewOfType1 addSubview:imageOfView];
    
    UIButton * tapBtn = [[UIButton alloc]initWithFrame:imageOfView.bounds];
    [tapBtn addTarget:self action:@selector(tapBtn:) forControlEvents:UIControlEventTouchUpInside];
    [imageOfView addSubview:tapBtn];
    
    UIButton * btn = [[UIButton alloc]init];
    if(types == 1)
    {
        btn.frame = CGRectMake(images.size.width , -10, 10, 10);
    }else if (types == 2)
    {
        btn.frame = CGRectMake(images.size.width , -10, 10, 10);
    }else if (types == 3)
    {
        btn.frame = CGRectMake(images.size.width , images.size.height, 10, 10);
    }else if (types == 4)
    {
        btn.frame = CGRectMake(self.viewOfType1.frame.size.width-30 , 25, 10, 10);
    }
    [btn setBackgroundImage:[UIImage imageNamed:@"关闭"] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(closeed:) forControlEvents:UIControlEventTouchUpInside];
    [imageOfView addSubview:btn];
    
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//        [self.viewOfType1 removeFromSuperview];
//    });
    
}

//第五种展现形式
-(void)showType5:(id)dic
{
    [self.view addSubview:self.folatingball];
    [self.folatingball addObserver:self forKeyPath:@"frame" options:NSKeyValueObservingOptionOld context:nil];
}

-(void)tapBtn:(UIButton *)btn
{
    NSLog(@"点击了弹窗");
}

-(void)closeed:(UIButton *)btn
{
    NSLog(@"点击了按钮");
    [self.viewOfType1 removeFromSuperview];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    UIImage *suspendedBallImage = [UIImage imageNamed:@"icon"];
    id oldName = [change objectForKey:NSKeyValueChangeOldKey];
    float centerX = self.folatingball.frame.origin.x+24;
    float centerY = self.folatingball.frame.origin.y+24;
    CGRect frame1 = self.btn.frame;
    
    if((centerX>self.view.bounds.size.width/2)&&(centerY>self.view.bounds.size.height/2))
    {
        frame1.origin.x = -10;
        frame1.origin.y = -10;
        self.btn.frame = frame1;
        
    }else if((centerX>self.view.bounds.size.width/2)&&(centerY<=self.view.bounds.size.height/2))
    {
        frame1.origin.x = -10;
        frame1.origin.y = suspendedBallImage.size.height ;
        self.btn.frame = frame1;
    }else if((centerX<self.view.bounds.size.width/2)&&(centerY>self.view.bounds.size.height/2))
    {
        frame1.origin.x = suspendedBallImage.size.height ;
        frame1.origin.y = -10;
        self.btn.frame = frame1;
    }else if((centerX<self.view.bounds.size.width/2)&&(centerY<=self.view.bounds.size.height/2))
    {
        frame1.origin.x = suspendedBallImage.size.width ;
        frame1.origin.y = suspendedBallImage.size.height ;
        self.btn.frame = frame1;
    }
    NSLog(@"oldName----------%f ---%@",self.folatingball.frame.origin.x,[oldName class]);
    
    id newName = [change objectForKey:NSKeyValueChangeNewKey];
    NSLog(@"newName-----------%@",newName);
    
    //当界面要消失的时候,移除kvo
    //    [object removeObserver:self forKeyPath:@"name"];
}


#pragma mark DismissButton
/** 添加《Dismiss》按钮 */
- (void)addDismissButton {
    CGFloat backBtnW = 80.0;
    UIButton *backBtn = [[UIButton alloc] initWithFrame:CGRectMake(FrameW - backBtnW - 10, 330, backBtnW, 30)];
    
    [backBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [backBtn setTitle:@"Dismiss" forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(backBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:backBtn];
}

- (void)backBtnClick {
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}

#pragma mark - Get
/**
 folatingball
 */
- (JhtFloatingBall *)folatingball {
    if (!_folatingball) {
       
        UIImage *suspendedBallImage = [UIImage imageNamed:@"icon"];
        _folatingball = [[JhtFloatingBall alloc] initWithFrame:CGRectMake(0, 20, suspendedBallImage.size.width , suspendedBallImage.size.height )];
        
        _folatingball.image = suspendedBallImage;
        _folatingball.stayAlpha = 0.6;
        _folatingball.delegate = self;
        _folatingball.userInteractionEnabled = YES;
        // 左右两侧停靠
        //        _folatingball.stayMode = (StayMode_OnlyLeft | StayMode_OnlyRight);
    
        
        UIButton * btn = [[UIButton alloc]initWithFrame:CGRectMake(suspendedBallImage.size.width , suspendedBallImage.size.height , 10, 10)];
        self.btn = btn;
        [btn setBackgroundImage:[UIImage imageNamed:@"关闭"] forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(close:) forControlEvents:UIControlEventTouchUpInside];
        [_folatingball addSubview:btn];
        
        //create sublayer
        self.blueLayer = [CALayer layer];
        self.blueLayer.frame = CGRectMake(0, 0, 10, 10);
        self.blueLayer.backgroundColor = [UIColor blueColor].CGColor;
        //add it to our view
        [self.btn.layer addSublayer:self.blueLayer];
       
    }
    
    return _folatingball;
}
/**
 关闭悬浮窗
 */
-(void)close:(UIButton *)btn
{
    [self.folatingball removeFromSuperview];
}

#pragma mark - JhtFloatingBallDelegate
/** folatingball点击 事件 */
- (void)tapFloatingBall {
    NSLog(@"folatingball 被点击了哈，爱管不管！！！");
}
/**
 *  重写touchesEnded方法
 */

- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    //get touch position relative to main view
    CGPoint point = [[touches anyObject] locationInView:self.view];
    //convert point to the white layer's coordinates
    point = [self.btn.layer convertPoint:point fromLayer:self.view.layer];
    //get layer using containsPoint:
    if ([self.btn.layer containsPoint:point]) {
        //convert point to blueLayer’s coordinates
        point = [self.blueLayer convertPoint:point fromLayer:self.btn.layer];
        if (![self.blueLayer containsPoint:point]) {
            [self.folatingball removeFromSuperview];
        }
    }
}
- (void)dealloc {
    [_folatingball removeObserver:self forKeyPath:@"frame"];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
